<?php

namespace app\admin\service;

use app\admin\model\Article;
use app\admin\model\Category;

/**
 * 栏目管理-服务类
 * Class CategoryService
 * @package app\admin\service
 */
class CategoryService extends BaseService
{
    /**
     * 构造函数
     *
     * CategoryService constructor.
     */
    public function __construct()
    {
        $this->model = new Category();
    }

    /**
     * 获取栏目列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];

        $name = getter($param, "name");
        if ($name) {
            $map[] = ["name", 'like', "%{$name}%"];
        }
        $list = $this->model->getList($map, "sort asc");


        foreach ($list as &$item) {
            $cateIds = $this->model->getSubs($item['id']);
            $cateIds[] = $item['id'];
            $item['courses'] = Article::where('cate_id', 'in', $cateIds)->where('mark', 1)->count();
            // $item['courses'] = Article::where('cate_id', $item['id'])->where('mark', 1)->count();

        }

        return message("操作成功", true, $list);
    }

    /**
     * 添加或编辑
     * @return mixed
     *
     */
    public function edit()
    {
        // 请求参数
        $data = request()->param();
        // 封面处理
        $cover = getter($data, 'cover');
        if (strpos($cover, "temp")) {
            $data['cover'] = save_image($cover, 'category');
        } else {
            $data['cover'] = str_replace(IMG_URL, "", $cover);
        }
        return parent::edit($data); // TODO: Change the autogenerated stub
    }

    /**
     * 获取栏目列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     */
    public function getCateList()
    {
        $list = $this->model->where([
            ['status', '=', 1],
            ['mark', '=', 1],
        ])->order("sort", "asc")
            ->select()
            ->toArray();
        return message("操作成功", true, $list);
    }

}